import time
import hmac
import hashlib
import base64
import urllib.parse
import requests


class DingTalk(object):

	def __init__(self, secret=None):
		self._timestamp = str(round(time.time() * 1000))
		secret = 'SECa8f7d3da23078061243e1e6855e85cd540221128201f2a9e08446cf454a73df9' if secret is None else secret
		secret_enc = secret.encode('utf-8')
		string_to_sign = '{}\n{}'.format(self._timestamp, secret)
		string_to_sign_enc = string_to_sign.encode('utf-8')
		hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
		self._sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

	def send_msg(self, content, at_all=True):
		_access_token = 'a92d98d2507fe6e290da674eaab703e84ef217c85de41f957e027596beec8f86'
		_baseUrl = 'https://oapi.dingtalk.com/robot/send?access_token={}'.format(_access_token)
		url = f'{_baseUrl}&timestamp={self._timestamp}&sign={self._sign}'

		_data = {
			'at': {
				'isAtAll': at_all
			},
			"text": {
				"content": content
			},
			"msgtype": "text"
		}
		response = requests.post(url, json=_data)
		return response.text


dingTalk = DingTalk()
